/* JimmApplication.java
 *
 * Copyright 2011 Aleksey Konovalov
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

package org.jimm.app;

import java.util.ArrayList;

import org.jimm.engine.AccountsManager;
import org.jimm.service.JimmService;
import org.jimm.service.JimmService.MyHandler;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

public class JimmApplication extends Application {

	private static final String LOG_TAG = "Jimm:JimmApplication";
	
	private static JimmApplication application;
	private Context applicationContext;
	private JimmService JimmService;
	private static boolean serviceStarted = false;
	public static boolean appStarted = false;
	private static ContentResolver contentResolver;
	// Очередь ожидания подключения сервиса
	private ArrayList<Runnable> serviceWaitQueue = new ArrayList<Runnable>();
	

	private final ServiceConnection JimmServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName className) {
			JimmService = null;
			serviceStarted = false;
		}

		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			JimmService = ((JimmService.LocalBinder) service).getService();
			synchronized (serviceWaitQueue) {
				for(Runnable r : serviceWaitQueue)
					r.run();
				serviceWaitQueue.clear();
			}
		}
	};

	public static final JimmApplication getApplication(Activity activity) {
		if (application == null)
			initialize(activity);
		return application;
	}
	
	protected void onPause() {
		Log.i(LOG_TAG, "onPause");
	}
	
	protected void onResume() {
		Log.i(LOG_TAG, "onResume"); 	
	}
	
	private static void initialize(Activity activity) {
		application = new JimmApplication();
		application.applicationContext = activity.getApplication();
		application.onCreate();
	}

	public JimmApplication() {
		super();
		application = this;
		this.applicationContext = this;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(LOG_TAG, "ServiceOnCreate");
		startJimmService();
		Log.i(LOG_TAG, "LangSysoc="+getResources().getConfiguration().locale.getDisplayName());
		
	}

	private void startJimmService() {
		Log.i(LOG_TAG, "LangSysss="+getResources().getConfiguration().locale.getDisplayName());
		if (JimmService == null) {
			
			Intent intent = new Intent( JimmService.ACTION_FOREGROUND);
		    intent.setClass(this, JimmService.class);
		    startService(intent);
			serviceStarted = true;
			Log.d(LOG_TAG, "StartService");
			applicationContext.bindService(intent, JimmServiceConnection,
					Context.BIND_AUTO_CREATE);
		}
	}

		
	private void stopJimmService() {
		
		JimmService JS = new JimmService();
		MyHandler handler;
		handler = JS.new MyHandler();
		if (serviceStarted) {
		
			//JimmService.stopSelf();
		
			org.jimm.service.JimmService.getAccountsManager().disconnectAll();
			handler.sendMessage(handler.obtainMessage(MyHandler.MESSAGE_SHOW_TOAST,"exit" ));
			serviceStarted = false;
			Log.d(LOG_TAG, "StopService");
			//stopService(new Intent(this, JimmService.class));
			
			//unbindService(JimmServiceConnection);
			JimmService=null;
			System.exit(0);
		}
		
	}
	
	

	public void callWhenServiceConnected(Runnable callback) {
		if(JimmService != null) {
			callback.run();
		} else {
			startJimmService();
			synchronized (serviceWaitQueue) {
				serviceWaitQueue.add(callback);
			}
		}
	}
	
	public AccountsManager getAccountsManager() {
		return JimmService != null ? JimmService.getAccountsManager()
				: null;
	}
	
	public JimmService getService() {
		return JimmService;
	}
	
	
	
	public static void closeApp()
	 {
		JimmApplication c=new JimmApplication(); 
		 c.stopJimmService();
	 }
		/*
	public void exit() {
		Log.d(LOG_TAG, "exit");
		//Log.i(LOG_TAG, "LangSys="+getResources().getConfiguration().locale.getDisplayName());
		stopService();
		super.onTerminate();
		System.exit(0);
	}*/
}
